package com.severez.bluetoothcontroller;

import java.util.List;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.severez.bluetoothcontroller.ble.BLEListeners.OnDataAvailableListener;
import com.severez.bluetoothcontroller.ble.BluetoothLeClass;
import com.severez.bluetoothcontroller.utils.MyDialogs;
import com.severez.bluetoothcontroller.utils.Utils;
import com.severez.bluetoothcontroller.value.Constant;
import com.umeng.update.UmengUpdateAgent;

public class MainActivity extends Activity {
    private final static String TAG = MainActivity.class.getSimpleName();

    private BluetoothLeClass mBLE;
    private Button btn_Scaning, btn_Setting, btn_Module, btn_ElectricCurrent, btn_Frequency, btn_Duration, btn_Start;
    private TextView tv_Module, tv_ElectricCurrent, tv_Frequency, tv_Duration;
    private TextView tv_Connected_Device;
    private Context mContext;

    private boolean isMatched, isRunning = false;

    // 用户选择的各项参数
    private int moduleNum = 1;
    private int moduleOrder = 0;
    private int electricCurrentOrder = 0;
    private int frequencyOrder = 0;
    private int durationOrder = 0;

    // private ProgressDialog pDialog;
    private Handler timeHandler = new Handler() {
	public void handleMessage(Message msg) {
	    super.handleMessage(msg);
	    Log.e(TAG, "----------timeHandler  timeout------");
	    instrumentStop();
	    MyDialogs.getAlertDialog(mContext, "通知", "本次治疗结束，谢谢使用！").setPositiveButton("确定", null).show();
	}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	UmengUpdateAgent.setUpdateOnlyWifi(false);
	UmengUpdateAgent.update(this);
	setContentView(R.layout.activity_main);
	mBLE = BluetoothLeClass.getInstance(this);
	mContext = MainActivity.this;

	findViews();

    }

    private void findViews() {
	btn_Scaning = (Button) findViewById(R.id.btn_scaning);
	tv_Connected_Device = (TextView) findViewById(R.id.tv_connecteddevice);

	btn_Module = (Button) findViewById(R.id.btn_Module);
	btn_ElectricCurrent = (Button) findViewById(R.id.btn_ElectricCurrent);
	btn_Frequency = (Button) findViewById(R.id.btn_Frequency);
	btn_Duration = (Button) findViewById(R.id.btn_Duration);
	btn_Start = (Button) findViewById(R.id.btn_Start);

	tv_Module = (TextView) findViewById(R.id.tv_Module);
	tv_ElectricCurrent = (TextView) findViewById(R.id.tv_ElectricCurrent);
	tv_Frequency = (TextView) findViewById(R.id.tv_Frequency);
	tv_Duration = (TextView) findViewById(R.id.tv_Duration);

	setListener();
    }

    private void setListener() {
	btn_Scaning.setOnClickListener(new OnClickListener() {
	    public void onClick(View v) {
		Intent intent = new Intent(MainActivity.this, ScaningActivity.class);
		startActivity(intent);
	    }
	});

	btn_Module.setOnClickListener(new OnClickListener() {
	    public void onClick(View v) {
		if (isMatched) {
		    new AlertDialog.Builder(mContext)
			    .setTitle("请选择")
			    .setSingleChoiceItems(
				    new String[] { Constant.module.get(0), Constant.module.get(1), Constant.module.get(2),
					    Constant.module.get(3) }, moduleOrder, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					    // pDialog =
					    // MyDialogs.getProgressDialog(mContext,
					    // R.string.is_setting);
					    // pDialog.show();
					    // mBLE.setOnDataAvailableListener(mOnDataAvailable);
					    // sendMsgToBLEDevice(which + 1);
					    moduleOrder = which;
					    tv_Module.setText(Constant.module.get(which));
					    dialog.dismiss();
					    if (isRunning) {
						sendMsgToBLEDevice(which + 1);
					    } else {
						moduleNum = which + 1;
					    }
					}
				    }).setNegativeButton("取消", null).show();
		} else {
		    alterIfNotMatched();
		}

	    }
	});

	btn_ElectricCurrent.setOnClickListener(new OnClickListener() {
	    public void onClick(View v) {
		if (isMatched) {
		    new AlertDialog.Builder(mContext)
			    .setTitle("请选择")
			    .setSingleChoiceItems(
				    new String[] { Constant.electricCurrent.get(0), Constant.electricCurrent.get(1),
					    Constant.electricCurrent.get(2), Constant.electricCurrent.get(3) }, electricCurrentOrder,
				    new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					    sendMsgToBLEDevice((which + 1) * 5);
					    electricCurrentOrder = which;
					    tv_ElectricCurrent.setText(Constant.electricCurrent.get(which));
					    dialog.dismiss();
					}
				    }).setNegativeButton("取消", null).show();
		} else {
		    alterIfNotMatched();
		}

	    }
	});

	btn_Frequency.setOnClickListener(new OnClickListener() {
	    public void onClick(View v) {
		if (isMatched) {
		    new AlertDialog.Builder(mContext)
			    .setTitle("请选择")
			    .setSingleChoiceItems(
				    new String[] { Constant.frequency.get(0), Constant.frequency.get(1), Constant.frequency.get(2),
					    Constant.frequency.get(3), Constant.frequency.get(4) }, frequencyOrder,
				    new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					    sendMsgToBLEDevice((which + 1) * 2 + 20);
					    frequencyOrder = which;
					    tv_Frequency.setText(Constant.frequency.get(which));
					    dialog.dismiss();
					}
				    }).setNegativeButton("取消", null).show();
		} else {
		    alterIfNotMatched();
		}

	    }
	});

	btn_Duration.setOnClickListener(new OnClickListener() {
	    public void onClick(View v) {
		if (isMatched) {
		    new AlertDialog.Builder(mContext)
			    .setTitle("请选择")
			    .setSingleChoiceItems(
				    new String[] { Constant.duration.get(0), Constant.duration.get(1), Constant.duration.get(2),
					    Constant.duration.get(3), Constant.duration.get(4),Constant.duration.get(5),Constant.duration.get(6) }, durationOrder,
				    new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					    durationOrder = which;
					    tv_Duration.setText(Constant.duration.get(which));
					    dialog.dismiss();
					    if (isRunning) {
						timeHandler.removeCallbacksAndMessages(null);
						timeHandler.sendEmptyMessageDelayed(0, Constant.duration_Actual.get(durationOrder));
					    } else {
						sendMsgToBLEDevice(which + 31);
					    }
					}
				    }).setNegativeButton("取消", null).show();
		} else {
		    alterIfNotMatched();
		}
	    }
	});

	btn_Start.setOnClickListener(new OnClickListener() {
	    public void onClick(View v) {
		if (!checkAllPamas()) {
		    MyDialogs.getAlertDialog(mContext, "通知", "请完成设置，再启动治疗仪").setPositiveButton("确定", null).show();
		    return;
		}
		if (isMatched) {
		    if (isRunning) {
			instrumentStop();
		    } else {
			sendMsgToBLEDevice(moduleNum);
			timeHandler.sendEmptyMessageDelayed(0, Constant.duration_Actual.get(durationOrder));
			Log.e(TAG, "Constant.duration_Actual.get(durationOrder)" + Constant.duration_Actual.get(durationOrder));
			isRunning = true;
			btn_Start.setText(R.string.btn_Stop);
		    }

		} else {
		    alterIfNotMatched();
		}
	    }
	});

    }

    private boolean checkAllPamas() {
	if (tv_Module.getText().equals("未设置") || tv_ElectricCurrent.getText().equals("未设置") || tv_Frequency.getText().equals("未设置")
		|| tv_Duration.getText().equals("未设置")) {
	    return false;
	} else {
	    return true;
	}
    }

    private void instrumentStop() {
	sendMsgToBLEDevice(255);
	timeHandler.removeCallbacksAndMessages(null);
	isRunning = false;
	btn_Start.setText(R.string.btn_Start);
    }

    private void alterIfNotMatched() {
	if (!isMatched) {
	    new AlertDialog.Builder(mContext).setMessage("请先配对治疗仪").setCancelable(false).setNegativeButton("确定", null).show();
	}
    }

    private void sendMsgToBLEDevice(int msg) {
	BluetoothGattService gattService = mBLE.mBluetoothGatt.getService(UUID.fromString(Constant.SERVICE_UUID));
	// BluetoothGattService gattService =
	// mBLE.mBluetoothGatt.getService(UUID.fromString(Constant.SERVICE_UUID_BONG_TEST));
	Log.e(TAG, "----------------------------------------------------------");

	final BluetoothGattCharacteristic characteristic_write = gattService
		.getCharacteristic(UUID.fromString(Constant.CHARACTERISTIC_MSG));
	// final BluetoothGattCharacteristic characteristic_write =
	// gattService.getCharacteristic(UUID
	// .fromString(Constant.CHARACTERISTIC_MSG_BONG_TEST));
	Log.e(TAG, "char uuid---->" + characteristic_write.getUuid());

	byte[] data = characteristic_write.getValue();
	if (data != null && data.length > 0) {
	    Log.e(TAG, "char value---->" + (int) data[0]);
	}

	mBLE.setCharacteristicNotification(characteristic_write, true);
	byte[] msgToSend = { (byte) msg };
	characteristic_write.setValue(msgToSend);
	mBLE.writeCharacteristic(characteristic_write);
    }

    @Override
    protected void onResume() {
	// TODO Auto-generated method stub
	super.onResume();
	if (mBLE.mBluetoothGatt == null) {
	    isMatched = false;
	    tv_Connected_Device.setText(R.string.tv_unconnect);
	} else if (mBLE.mBluetoothGatt.getDevice() == null) {
	    isMatched = false;
	    tv_Connected_Device.setText(R.string.tv_unconnect);
	} else {
	    isMatched = true;
	    tv_Connected_Device.setText("已配对治疗仪： " + mBLE.mBluetoothGatt.getDevice().getName());
	}
    }

    @Override
    protected void onDestroy() {
	// TODO Auto-generated method stub
	super.onDestroy();
	mBLE.disconnect();
	mBLE.close();
	timeHandler.removeCallbacksAndMessages(null);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
	if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	    MyDialogs.getAlertDialog(MainActivity.this, "请选择", "是否退出软件？").setPositiveButton("是", new AlertDialog.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		    // TODO Auto-generated method stub
		    MainActivity.this.finish();
		}
	    }).setNegativeButton("否", null).setCancelable(true).show();
	    return true;
	} else
	    return super.onKeyDown(keyCode, event);
    }

    /**
     * 收到BLE终端数据交互的事件
     */
    private OnDataAvailableListener mOnDataAvailable = new OnDataAvailableListener() {
	/**
	 * BLE终端数据被读的事件
	 */
	@Override
	public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
	    Log.e(TAG, "-----------------onCharacteristicRead  scanactivity----------------------" + status);
	    if (status == BluetoothGatt.GATT_SUCCESS) {
		Log.e(TAG, "onCharRead " + "  device nama: " + gatt.getDevice().getName() + "  char uuid: "
			+ characteristic.getUuid().toString() + "  value: " + characteristic.getValue()[0]);
	    }
	}

	/**
	 * 收到BLE终端写入数据回调
	 */
	@Override
	public void onCharacteristicWritten(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
	    Log.e(TAG, "status--->" + status + " onCharWrite " + "  device nama: " + gatt.getDevice().getName() + "  char uuid: "
		    + characteristic.getUuid().toString() + "  value: " + characteristic.getValue()[0]);
	}

	public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
	    Log.e(TAG,
		    " onCharacteristicChanged " + "  char uuid: " + characteristic.getUuid().toString() + "  value: "
			    + characteristic.getValue()[0]);
	};
    };

}
